package com.bo.weibo;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bo.WeiboConfig;
import com.bo.gather.bean.GatherBean;
import com.bo.gather.bean.weibo.IncludeNotFileInfo;
import com.bo.gather.bean.weibo.OrderLengthinfo;
import com.bo.gather.bean.weibo.WeiboBean;
import com.bo.gather.bean.weibo.WeiboRuleBean;
import com.bo.gather.rule.RuleAnalyse;
import com.bo.sina.weibo.share.Share;
import com.bo.util.IOUtil;
import com.bo.weibo.bean.SendDataInfo;
import com.bo.weibo.bean.WeiboSendBean;

public class WeiboService {
	static Logger log = Logger.getLogger(WeiboService.class.getName());
	
	
	public void sendWeibo(WeiboSendBean weibo,SendDataInfo sdi,GatherBean gatherbean){

		this.setweibonick(sdi,weibo.getAccessInfo().getNick());
		Share share=new Share();
		try {
			share.share(weibo.getAccessInfo(), sdi);
			log.info("《"+gatherbean.getTitle()+"》发成功  "+weibo.getAccessInfo().getNick()+
					"     内容为："+java.net.URLDecoder.decode(sdi.getContent(), "utf-8"));
		} catch (Exception e) {
			try {
				log.error("监控到《"+gatherbean.getTitle()+"》发失败，微博账号为"+weibo.getAccessInfo().getNick()+
						" 内容为："+java.net.URLDecoder.decode(sdi.getContent(), "utf-8"),e);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		
		//无论发送成功与否都 记录
		IOUtil.writeEndData(WeiboConfig.getValue("gatherRepeatData").trim()+weibo.getAccessInfo().getNick(), sdi.getOnlyid()+"\r\n", "UTF-8");
	}
	
	
	
//	public void sendWeibo(WeiboSendBean weibo,SendDataInfo sdi,GatherBean gatherbean){
//		Timeline tm = new Timeline();  
//		tm.setToken(weibo.getAccessToken());
//		Status status=null;
//		this.setweibonick(sdi,weibo.getScreenName());
////		log.info("监控到《"+gatherbean.getTitle()+"》，账号为"+weibo.getScreenName()+" 内容为："+sdi.getContent());
//		if(sdi.getImageItem()!=null){
//			try {
//				status=tm.UploadStatus(sdi.getContent(), sdi.getImageItem());
//				log.info("《"+gatherbean.getTitle()+"》发成功   "+status.getUser().getScreenName()+"   内容为："+status.getText());
//			} catch (WeiboException e) {
//				try {
//					String s=java.net.URLDecoder.decode(sdi.getContent(), "utf-8");
//					log.error("监控到《"+gatherbean.getTitle()+"》发失败，微博账号为"+weibo.getScreenName()+" 内容为："+s,e);
//				} catch (UnsupportedEncodingException e1) {
//					e1.printStackTrace();
//				}
//			}
//		}else{
//			try {
//				status=tm.UpdateStatus(sdi.getContent());
//				log.info("《"+gatherbean.getTitle()+"》发成功  "+status.getUser().getScreenName()+"     内容为："+status.getText());
//			} catch (WeiboException e) {
//				try {
//					String s=java.net.URLDecoder.decode(sdi.getContent(), "utf-8");
//					log.error("监控到《"+gatherbean.getTitle()+"》发失败，微博账号为"+weibo.getScreenName()+" 内容为："+s,e);
//				} catch (UnsupportedEncodingException e1) {
//					e1.printStackTrace();
//				}
//			}
//		}
//		//无论发送成功与否都 记录
//		IOUtil.writeEndData(WeiboConfig.getValue("gatherRepeatData").trim()+weibo.getScreenName(), sdi.getOnlyid()+"\r\n", "UTF-8");
//	}
	private void setweibonick(SendDataInfo obj,String temp2){
		StringBuffer sendcontent=new StringBuffer();
		//追加@ 小于120个字才能加 并且加入的内容不能大于126个字 因为要留个后门的URL
		if(temp2.equals("今日热门视频") && obj.getContent().length()<120){
			String nick=SearchAccount.getAccountNick(obj.getContent());
			if(2+nick.length()+obj.getContent().length()<126){
				sendcontent.append("@");
				sendcontent.append(nick);
				sendcontent.append(" ");
			}
		}
		//增加url 大于126个字必须截取
		if(obj.getUrl()!=null && obj.getUrl().length()>0){
			if(obj.getContent().length()>126){
//				String temp=sendcontent.substring(0,126);
//				sendcontent.delete(0, sendcontent.length());

				sendcontent.append("...");
				sendcontent.append(obj.getUrl());
			}else{
				sendcontent.append(obj.getUrl());
			}
		}
		if(obj.getContent().length()>126){
			String temp=obj.getContent().substring(0,126);
			obj.setContent(temp+sendcontent.toString());
		}else{
			obj.setContent(obj.getContent()+sendcontent.toString());
		}
		try {
//			log.info("前............"+obj.getContent());
			 obj.setContent(java.net.URLEncoder.encode(obj.getContent(), "utf-8"));
//			log.info("后............"+obj.getContent());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 计算发送微博的内容
	 * @param gatherList
	 * @param weiboRuleBean
	 * @return
	 */
	public List<SendDataInfo> calculateSendData(List<Map<String,String>> gatherList,WeiboRuleBean weiboRuleBean,String onlyidsign){
		List<SendDataInfo> list=new ArrayList<SendDataInfo>();
		for(Map<String,String> map:gatherList){
			SendDataInfo sendDataInfo=this.calculateWeibo(map, weiboRuleBean,onlyidsign);
			if(sendDataInfo!=null){
				list.add(sendDataInfo);
			}
		}
		if(list.size()>0){
			return list;
		}
		return null;
	}
	
	private SendDataInfo calculateWeibo(Map<String,String> contentMap,WeiboRuleBean weiboRuleBean,String onlyidsign){
		SendDataInfo sendDataInfo=new SendDataInfo();
		
		StringBuffer sendcontent =new StringBuffer();
		WeiboBean titlebean=weiboRuleBean.getTitleBean();
		String title=contentMap.get(titlebean.getName());
		if(title!=null){
			String isdelete=RuleAnalyse.calculateLength(title, titlebean.getLengthinfo());
			if(!RuleAnalyse.returnpass.equals(isdelete)){
				if(isdelete.equals(RuleAnalyse.delete)){
					title=null;
				}else if(isdelete.equals(RuleAnalyse.alldelete)){
					return null;
				}
			}else{
				OrderLengthinfo orderLengthinfo=titlebean.getOrderLengthinfo();
				String content=contentMap.get(orderLengthinfo.getName());
				if(content!=null){
					isdelete=RuleAnalyse.calculateOrderLength(content, orderLengthinfo);
					if(RuleAnalyse.returnpass.equals(isdelete)){
						sendcontent.append("#");
						sendcontent.append(title);
						sendcontent.append("#");
					}else{
						sendcontent.append(title);
						sendcontent.append(" ");
					}
				}else{
					sendcontent.append(title);
					sendcontent.append(" ");
				}
			}
		}
		
		//处理内容
		WeiboBean contentbean=weiboRuleBean.getContentBean();
		String content=contentMap.get(contentbean.getName());
		if(content!=null){
			String isdelete=RuleAnalyse.calculateLength(title, contentbean.getLengthinfo());
			if(!RuleAnalyse.returnpass.equals(isdelete)){
				if(isdelete.equals(RuleAnalyse.delete)){
					
				}else if(isdelete.equals(RuleAnalyse.alldelete)){
					return null;
				}
			}else{
				IncludeNotFileInfo includeNotFileInfo=contentbean.getIncludeNotFileInfo();
				String target=contentMap.get(includeNotFileInfo.getTargetFile());
				isdelete=RuleAnalyse.calculateIncludeNotFile(content, includeNotFileInfo, target);
				if(RuleAnalyse.returnpass.equals(isdelete)){
					sendcontent.append(content);
				}
			}
		}
//		//追加@
//		if(sendcontent.toString().length()<130){
//			String nick=SearchAccount.getAccountNick(sendcontent.toString());
//			if(2+nick.length()+sendcontent.toString().length()<130){
//				sendcontent.append("@");
//				sendcontent.append(nick);
//				sendcontent.append(" ");
//			}
//		}
		
		String url=contentMap.get(weiboRuleBean.getUrl());
		if(url!=null){
			sendDataInfo.setUrl(url);
//			if(sendcontent.toString().length()>126){
//				String temp=sendcontent.substring(0,126);
//				sendcontent.delete(0, sendcontent.length());
//				sendcontent.append(temp);
//				sendcontent.append("...");
//				sendcontent.append(url);
//			}else{
//				sendcontent.append(url);
//			}
		}
		sendDataInfo.setContent(sendcontent.toString());
		//f发送图片
        if(weiboRuleBean.getImageUrl()!=null){
            //微博API规定，有图片的话，必须转码为UTF-8
//          try {
//              String s = java.net.URLEncoder.encode(sendcontent.toString(), "utf-8");
//              sendDataInfo.setContent(s);
//          } catch (UnsupportedEncodingException e1) {
//              e1.printStackTrace();
//          }
            
//          byte[] imagecontent = Image.getImageFromURL(contentMap.get(weiboRuleBean.getImageUrl()));
//          try {
//              ImageItem pic = new ImageItem("pic", imagecontent);
//              sendDataInfo.setImageItem(pic);
//          } catch (WeiboException e) {
//              e.printStackTrace();
//          }
            sendDataInfo.setImageurl(contentMap.get(weiboRuleBean.getImageUrl()));
        }
		//设置唯一标示符
		sendDataInfo.setOnlyid(contentMap.get(onlyidsign));
		
		return sendDataInfo;
	}
	

}
